//
//  UIView+LLYDebug.m
//  LvYue
//
//  Created by edz on 2020/11/3.
//  Copyright © 2020 悦商集团. All rights reserved.
//

#import "UIView+Debug.h"
#import <objc/message.h>
#import "UIColor+JGHexColor.h"


@implementation UIView (Debug)
static BOOL YS_VIEW_FRAME_VISIBLE = NO;

+ (void)ys_setFrameVisible:(BOOL)visible {
    YS_VIEW_FRAME_VISIBLE = visible;
}

#ifdef DEBUG
+ (void)load {
    swizzleMethod(self, @selector(didMoveToSuperview), @selector(ys_didMoveToSuperview));
}


- (void)ys_didMoveToSuperview{
    if (YS_VIEW_FRAME_VISIBLE && self.layer.borderWidth == 0) {
        self.layer.borderWidth = 1;
        self.layer.borderColor = [[UIColor jg_randomColor] colorWithAlphaComponent:0.3].CGColor;
    }
    [self ys_didMoveToSuperview];
}

#endif

void swizzleMethod(Class class, SEL originalSelector, SEL swizzledSelector)
{
    // the method might not exist in the class, but in its superclass
    Method originalMethod = class_getInstanceMethod(class, originalSelector);
    Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
    
    // class_addMethod will fail if original method already exists
    BOOL didAddMethod = class_addMethod(class, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod));
    
    // the method doesn’t exist and we just added one
    if (didAddMethod) {
        class_replaceMethod(class, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
    }
    else {
        method_exchangeImplementations(originalMethod, swizzledMethod);
    }
    
}


@end
